using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Xml;

namespace SideShow.Scf.ObjectModel
{
    [Serializable]
    public class ScfDocument : ScfObject
    {
        private ScfBodyElement _body;

        public ScfBodyElement Body
        {
            get { return _body; }
            set { _body = value; }
        }

        public static ScfDocument Load(XmlDocument doc)
        {
            XmlDocument rawDoc = doc;
            ScfDocument scfDoc = new ScfDocument();
            scfDoc.DeserializeFromXml(doc.DocumentElement);
            return scfDoc;
        }

        protected internal override void DeserializeFromXml(XmlNode node)
        {
            base.DeserializeFromXml(node);
            if (node.FirstChild != null)
            {
                _body = null;
                switch (node.FirstChild.LocalName)
                {
                    case "menu":
                        _body = new ScfMenu();
                        break;
                    case "dialog":
                        _body = new ScfDialog();
                        break;
                    case "content":
                        _body = new ScfContent();
                        break;
                    default:
                        throw new Exception("Invalid body child element: " + node.FirstChild.LocalName);
                }
                _body.DeserializeFromXml(node.FirstChild);
            }
        }

        protected internal override void SerializeObject(System.IO.BinaryWriter writer)
        {
            base.SerializeObject(writer);
            writer.Write(GetTypeName(_body));
            _body.SerializeObject(writer);
        }

        protected internal override void DeserializeObject(System.IO.BinaryReader reader)
        {
            base.DeserializeObject(reader);
            string typeName = reader.ReadString();
            Type t = FindType(typeName);
            _body = (ScfBodyElement)Activator.CreateInstance(t);
            _body.DeserializeObject(reader);
        }
        
    }
}
